package com.atguigu.jucdemo;

import com.atguigu.jucdemo.test.SaleTicketDemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.util.concurrent.TimeUnit;

@SpringBootApplication
public class JucDemoApplication {

    public static void main(String[] args) {
        /*SaleTicketDemo t = new SaleTicketDemo();

        Thread t1 = new Thread(t,"赵四");
        Thread t2 = new Thread(t,"广坤");
        Thread t3 = new Thread(t,"刘能");

        t1.start();
        t2.start();
        t3.start();*/
        Ticket ticket = new Ticket();
        //v1
        /*new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 1; i <= 50; i++) {
                    ticket.sale();
                }
            }
        }, "赵四").start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 1; i <= 50; i++) {
                    ticket.sale();
                }
            }
        }, "王五").start();*/



        //v2
        new Thread(() -> {
            for (int i = 1; i <= 50; i++) ticket.sale();
        }, "张三").start();
        new Thread(() -> {
            for (int i = 1; i <= 50; i++) ticket.sale();
        }, "赵四").start();
        new Thread(() -> {
            for (int i = 1; i <= 50; i++) ticket.sale();
        }, "王五").start();

    }

}

class Ticket {
    private int num = 50;

    public synchronized void sale() {
        if (num > 0) {
            System.out.println(Thread.currentThread().getName() + "取走了第" + (num--) + "张票" + "还剩余" + num + "张");
            try {
                TimeUnit.MILLISECONDS.sleep(200);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
